package com.hulu.yec.stu.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;








import com.hulu.yec.common.Constant;
import com.hulu.yec.common.exception.DaoRuntimeException;
import com.hulu.yec.common.util.DBUtil;
import com.hulu.yec.common.util.LogUtil;
import com.hulu.yec.sys.user.service.SysUserDao;
import com.hulu.yec.teach.testpaper.entity.TestPaperEntity;
import com.hulu.yec.teach.testquestion.enetity.QuestionEntity;

/**
 * 进行考试
 * 
 * @author hf001
 * 2016年3月23日
 */
public class ExamDao {

	/**
	 * 通过id的到试卷信息
	 * 
	 * @param id
	 * @return
	 */
	public TestPaperEntity getPaper(String id) {
		String sql = "SELECT * FROM qes_exam_paper WHERE id=?";
		return new SysUserDao().getUniqueResult(TestPaperEntity.class,sql, id);
	}

	/**
	 * 通过类型和编号的到问题信息
	 * 
	 * @param choicetype
	 * @param singleOptionNumber
	 * @return
	 */
	public List<QuestionEntity> getQuestion(int choicetype,
			int singleOptionNumber) {
		String sql = "select * from qes_qestions where question_type=? order by rand() limit ?";
		return new SysUserDao().excuteQuery(QuestionEntity.class, sql, choicetype,singleOptionNumber);
	}
	
	/**
	 * 得到正确答案
	 * 
	 * @param type
	 * @param number
	 * @return
	 */
	public String getRightAnswer(int type,
			String number) {
		String sql = "select * from qes_qestions where question_type=? AND id = ?";
		QuestionEntity questionEntity= new SysUserDao().getUniqueResult(QuestionEntity.class, sql, type,number);
		return questionEntity.getAnswer();
	}


	/**
	 * 判断选择题答案是否争确
	 * 
	 * @param type
	 * @param number
	 * @param answer
	 * @return
	 */
	public boolean isRight(int type, String number, String answer) {
		if(getRightAnswer(type,number).equals(answer)){
			return true;
		}
		return false;
	}

	public void addRecord(int userId, String planId, int score, Date endTime,
			Date startTime,int isPass) {
		String sql = "INSERT INTO exam_records VALUES(NULL, ?, ?, ?, ?, ?, ?)";
		List<Object> param = new ArrayList();
		param.add(userId);
		param.add(planId);
		param.add(score);
		param.add(endTime);
		param.add(startTime);
		param.add(isPass);
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = DBUtil.getConnection();
			preparedStatement = connection.prepareStatement(sql);
			DBUtil.setParameter(param, preparedStatement);
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			LogUtil.e(Constant.LOGGER, "改变用户状态失败！", e);
			throw new DaoRuntimeException("改变用户状态失败！");
		} finally {
			DBUtil.close(connection, preparedStatement);
		}
		
	}

}
